<script setup>
import { onMounted, reactive, ref } from 'vue'
import { queryIcon } from '@api/city-index'
import { Message } from 'element-ui'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
})

const selectIconIndex = ref(-1)

const form = reactive({
  name: '',
  icon: '',
})

const rules = {
  name: [{ required: true, message: '请输入维度名称', trigger: 'blur' }],
}

const formRef = ref()

const emit = defineEmits(['closed', 'confirm'])

const handleClosed = () => {
  emit('closed')
}

const convertImageToBase64 = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}

const fileList = ref([])

const handleChangeFile = (file) => {
  convertImageToBase64(file.raw).then((res) => {
    form.icon = res
    selectIconIndex.value = -1
    Message.success('上传成功')
  })
}

const handleRemoveFile = () => {
  selectIconIndex.value = -1
  form.icon = ''
  Message.success('删除成功')
}

const handleCancel = () => {
  emit('closed')
}

const handleConfirm = () => {
  formRef.value.validate().then((valid) => {
    if (valid) {
      emit('confirm', form)
    }
  })
}

const iconList = ref([])

const selectIcon = (index, item) => {
  if (selectIconIndex.value === index) {
    selectIconIndex.value = -1
    form.icon = ''
  } else {
    selectIconIndex.value = index
    form.icon = item.content
    form.name = item.name
  }
  fileList.value = []
}

const getIconList = () => {
  queryIcon().then((res) => {
    if (res.success) {
      iconList.value = res.data.map((item) => {
        return {
          ...item,
          icon: item.content
            ? URL.createObjectURL(
                new Blob([item.content], {
                  type: 'text/xml',
                })
              )
            : null,
        }
      })
    }
  })
}

onMounted(() => {
  getIconList()
})

const handleOpen = () => {
  selectIconIndex.value = ''
  fileList.value = []
}

const inputData = (data) => {
  Object.assign(form, data)
}

defineExpose({
  inputData,
})
</script>

<template>
  <el-dialog
    title="新增视角"
    :visible="visible"
    width="40%"
    @open="handleOpen"
    @close="handleClosed"
    class="add-dimension-dialog"
  >
    <el-form ref="formRef" :model="form" label-width="120px" :rules="rules">
      <el-form-item label="维度名称" prop="name">
        <el-input type="text" v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="常用图标" prop="icon">
        <div class="grid">
          <div
            :class="['icon-item', selectIconIndex === index ? 'active' : '']"
            v-for="(item, index) of iconList"
            :key="index"
            @click="selectIcon(index, item)"
          >
            <img :src="item.content" />
            <span>{{ item.name }}</span>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="上传图标">
        <el-upload
          action=""
          ref="uploadRef"
          :limit="1"
          :file-list="fileList"
          accept=".png,.jpeg,.jpg"
          :auto-upload="false"
          :on-change="handleChangeFile"
          :on-remove="handleRemoveFile"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">
            只能上传jpg/png文件，且不超过100kb
          </div>
        </el-upload>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="handleConfirm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<style scoped>
.add-dimension-dialog {
  .grid {
    position: relative;
    display: grid;
    grid-template-columns: repeat(4, 25%);

    .icon-item {
      padding: 20px;
      height: 50px;
      text-align: center;
      width: 100px;
      float: left;
      font-size: 30px;
      color: #24292e;
      cursor: pointer;

      img {
        width: 50px;
        height: 40px;
        padding: 0 5px;
        box-sizing: border-box;
      }

      &.active {
        border-color: #c5e3f1;
        background-color: #ecf6fb;
      }
    }

    span {
      display: block;
      width: 100px;
      height: 20px;
      font-size: 16px;
      line-height: 20px;
    }
  }
}
</style>
